package com.doge.service.admin.promotion;

/**
 * promotion包里的都是推广模块下
 * 此CouponServiceImpl是负责优惠券管理
 * Created By ntian
 */

import com.alibaba.druid.util.StringUtils;
import com.doge.bean.base.BaseData;
import com.doge.bean.base.BaseParam;
import com.doge.bean.pojo.coupon.Coupon;
import com.doge.bean.pojo.coupon.CouponExample;
import com.doge.bean.pojo.coupon.CouponUser;
import com.doge.bean.pojo.coupon.CouponUserExample;
import com.doge.bean.vo.coupon.CouponGoodsVO;
import com.doge.exception.Param402Exception;
import com.doge.mapper.CouponMapper;
import com.doge.mapper.CouponUserMapper;
import com.doge.util.converter.DateConverter;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class CouponServiceImpl implements CouponService{
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    CouponUserMapper couponUserMapper;

    /**
     * 在CouponExample和CouponMapper.xml里面，所有的`limit`,`desc`,`type`都要进行处理
     * @param baseParam
     * @param name
     * @param status
     * @param type 字段是SQL里面的关键词，注意加入`type`
     * @return BaseData 里面是分页数据和一个list数组
     */

    @Override
    public BaseData listCoupon(BaseParam baseParam, String name, Short status, Short type) {
        PageHelper.startPage(baseParam.getPage(),baseParam.getLimit());
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria = couponExample.createCriteria();
        //设置只有deleted = false（0）的时候才显示
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(name)){
            criteria.andNameLike("%"+name+"%");
        }
        if (status != null && status != 0){
            criteria.andStatusEqualTo(status);
        }
        if (type != null && type != 0){
            criteria.andTypeEqualTo(type);
        }

        couponExample.setOrderByClause(baseParam.getSort()+" "+baseParam.getOrder());
        List<Coupon> couponList= couponMapper.selectByExample(couponExample);

        PageInfo pageInfo = new PageInfo(couponList);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();

        BaseData data = BaseData.list(couponList, total);
        data.setLimit(baseParam.getLimit());
        data.setPage(baseParam.getPage());
        data.setPages(pages);
        return data;
    }

    @Override
    public Coupon listReadCoupon(Integer id) {
        Coupon coupon= couponMapper.selectByPrimaryKey(id);
        return coupon;
    }

    /**
     * 显示的是某一个特定的用户有什么优惠券
     * @param baseParam 分页的数据
     * @param couponId 优惠券的id
     * @param userId 用户的id
     * @param status 优惠券的状态，用没有用过
     * @return 分页数据+list
     */

    @Override
    public BaseData listUserCoupons(BaseParam baseParam, Integer couponId, Integer userId, Short status) {
        PageHelper.startPage(baseParam.getPage(),baseParam.getLimit());
        CouponUserExample example = new CouponUserExample();
        CouponUserExample.Criteria criteria = example.createCriteria();
        if (couponId != null && couponId != 0){
            criteria.andCouponIdEqualTo(couponId);
        }
        if (userId != null && userId != 0){
            criteria.andUserIdEqualTo(userId);
        }
        if(status != null && status != 0){
            criteria.andStatusEqualTo(status);
        }

        example.setOrderByClause(baseParam.getSort()+" "+baseParam.getOrder());
        List<CouponUser> userList = couponUserMapper.selectByExample(example);

        PageInfo pageInfo = new PageInfo(userList);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();

        BaseData data = BaseData.list(userList, total);
        data.setLimit(baseParam.getLimit());
        data.setPage(baseParam.getPage());
        data.setPages(pages);
        return data;

    }

    @SneakyThrows
    @Override
    public int createCoupon(CouponGoodsVO couponGoodsVO) {
        /**
         * 对优惠券的参数进行校验
         * discount: 可以满减的金额，min:最低消费金额，limit：每人限领优惠券的数量，total：优惠券的数量
         * 如果满减的金额大于最低消费额，抛出满减金额大于最低消费金额的异常
         * 每人限领的优惠券的数量limit大于优惠券的数量total
         * 优惠券结束的日期不能早于优惠券生效的开始日期
         */
        BigDecimal discount = couponGoodsVO.getDiscount();
        BigDecimal min = couponGoodsVO.getMin();
        Short limit = couponGoodsVO.getLimit();
        Integer total = couponGoodsVO.getTotal();
        Date startTime = couponGoodsVO.getStartTime();
        Date endTime = couponGoodsVO.getEndTime();
        String desc = couponGoodsVO.getDesc();
        String tag = couponGoodsVO.getTag();
        Short type = couponGoodsVO.getType();
        Short status = couponGoodsVO.getStatus();
        Short goodsType = couponGoodsVO.getGoodsType();
        Short timeType = couponGoodsVO.getTimeType();
        Short days = couponGoodsVO.getDays();
        Date updateTime = couponGoodsVO.getUpdateTime();
        Date addTime = couponGoodsVO.getAddTime();

        if (discount.compareTo(min)>0){
            throw new Param402Exception("参数异常!满减金额大于最低消费金额!");
        }
//        if (limit>total){
//            throw new Param402Exception("参数异常!每人限领的优惠券的数量大于优惠券的数量total");
//        }
        if (endTime !=null || startTime!= null){
            if(endTime ==null || startTime == null){
                throw new Param402Exception("参数异常！未缺少一个时间数据");
            }
            if (endTime.before(startTime)){
                throw new Param402Exception("参数异常!优惠券结束的日期不能早于优惠券生效的开始日期!");
            }
        }
        Coupon coupon = new Coupon();
        coupon.setDiscount(discount);
        coupon.setMin(min);
        coupon.setLimit(limit);
        if (total!=null){
            coupon.setTotal(total);
        }
        if (startTime!=null&&endTime!=null){
            coupon.setStartTime(startTime);
            coupon.setEndTime(endTime);
        }else{
            coupon.setStartTime(null);
            coupon.setEndTime(null);
        }
        if (!StringUtils.isEmpty(couponGoodsVO.getName())){
            coupon.setName(couponGoodsVO.getName());
        }
        if (!StringUtils.isEmpty(desc)){
            coupon.setDesc(desc);
        }
        if (!StringUtils.isEmpty(tag)){
            coupon.setTag(tag);
        }
        if (!StringUtils.isEmpty(String.valueOf(type))){
            coupon.setType(type);
        }
        if (!StringUtils.isEmpty(String.valueOf(goodsType))){
            coupon.setGoodsType(goodsType);
        }
        if (!StringUtils.isEmpty(String.valueOf(timeType))){
            coupon.setTimeType(timeType);
        }
        if (!StringUtils.isEmpty(String.valueOf(days))){
            coupon.setDays(days);
        }
        if (!StringUtils.isEmpty(String.valueOf(status))){
            coupon.setStatus(status);
        }
        int rows = couponMapper.insertSelective(coupon);
        return rows;
    }

    /**
     * 对优惠券coupon进行逻辑删除
     * @param coupon
     * @return 被逻辑删除的优惠券的数量
     */
    @Override
    public int deleteCoupon(Coupon coupon) {
        coupon.setDeleted(true);
        int rows = couponMapper.updateByPrimaryKeySelective(coupon);
        return rows;
    }

    @SneakyThrows
    @Override
    public int updateCoupon(CouponGoodsVO couponGoodsVO) {
        /**
         * 对优惠券的参数进行校验
         * discount: 可以满减的金额，min:最低消费金额，limit：每人限领优惠券的数量，total：优惠券的数量
         * 如果满减的金额大于最低消费额，抛出满减金额大于最低消费金额的异常
         * 每人限领的优惠券的数量limit大于优惠券的数量total
         * 优惠券结束的日期不能早于优惠券生效的开始日期
         */
        BigDecimal discount = couponGoodsVO.getDiscount();
        BigDecimal min = couponGoodsVO.getMin();
        Short limit = couponGoodsVO.getLimit();
        Integer total = couponGoodsVO.getTotal();
        Date startTime = couponGoodsVO.getStartTime();
        Date endTime = couponGoodsVO.getEndTime();
        String desc = couponGoodsVO.getDesc();
        String tag = couponGoodsVO.getTag();
        Short type = couponGoodsVO.getType();
        Short status = couponGoodsVO.getStatus();
        Short goodsType = couponGoodsVO.getGoodsType();
        Short timeType = couponGoodsVO.getTimeType();
        Short days = couponGoodsVO.getDays();
        Date updateTime = couponGoodsVO.getUpdateTime();
        Date addTime = couponGoodsVO.getAddTime();
        if (discount.compareTo(min)>0){
            throw new Param402Exception("参数异常!满减金额大于最低消费金额!");
        }
        if (endTime !=null || startTime!= null){
            if(endTime ==null || startTime == null){
                throw new Param402Exception("参数异常！未缺少一个时间数据");
            }
            if (endTime.before(startTime)){
                throw new Param402Exception("参数异常!优惠券结束的日期不能早于优惠券生效的开始日期!");
            }
        }
        Coupon coupon = new Coupon();
        coupon.setDiscount(discount);
        coupon.setMin(min);
        coupon.setLimit(limit);
        if (total!=null){
            coupon.setTotal(total);
        }
        if (startTime!=null&&endTime!=null){
            coupon.setStartTime(startTime);
            coupon.setEndTime(endTime);
        }else{
            coupon.setStartTime(null);
            coupon.setEndTime(null);
        }
        if (!StringUtils.isEmpty(couponGoodsVO.getName())){
            coupon.setName(couponGoodsVO.getName());
        }
        if (!StringUtils.isEmpty(desc)){
            coupon.setDesc(desc);
        }
        if (!StringUtils.isEmpty(tag)){
            coupon.setTag(tag);
        }
        if (!StringUtils.isEmpty(String.valueOf(type))){
            coupon.setType(type);
        }
        if (!StringUtils.isEmpty(String.valueOf(goodsType))){
            coupon.setGoodsType(goodsType);
        }
        if (!StringUtils.isEmpty(String.valueOf(timeType))){
            coupon.setTimeType(timeType);
        }
        if (!StringUtils.isEmpty(String.valueOf(days))){
            coupon.setDays(days);
        }
        if (!StringUtils.isEmpty(String.valueOf(status))){
            coupon.setStatus(status);
        }
        int rows = couponMapper.updateByPrimaryKeySelective(coupon);
        return rows;
    }


}